from sqlalchemy.orm import Session
from sqlalchemy import desc
from backend.models import Device, Backup
from backend.config import settings
import os
import logging

logger = logging.getLogger(__name__)

class CleanupService:
    """备份清理服务"""
    
    def __init__(self, db: Session):
        self.db = db
        self.max_backups_per_device = 3  # 每个设备最多保留3个备份
    
    def set_max_backups(self, max_backups: int):
        """设置每个设备最大保留备份数量"""
        if max_backups < 1 or max_backups > 50:
            raise ValueError("备份保留数量必须在1-50之间")
        self.max_backups_per_device = max_backups
        return max_backups
    
    def cleanup_old_backups(self):
        """清理旧备份，每个设备只保留最新的N个备份"""
        try:
            # 获取所有设备
            devices = self.db.query(Device).all()
            cleaned_count = 0
            
            for device in devices:
                # 获取该设备的所有成功备份，按时间倒序
                backups = self.db.query(Backup).filter(
                    Backup.device_id == device.id,
                    Backup.status == 'success'
                ).order_by(desc(Backup.backup_time)).all()
                
                # 如果备份数量超过限制，删除多余的
                if len(backups) > self.max_backups_per_device:
                    backups_to_delete = backups[self.max_backups_per_device:]
                    
                    for backup in backups_to_delete:
                        # 删除文件
                        if os.path.exists(backup.filepath):
                            try:
                                os.remove(backup.filepath)
                                logger.info(f"已删除备份文件: {backup.filepath}")
                            except Exception as e:
                                logger.error(f"删除文件失败 {backup.filepath}: {str(e)}")
                        
                        # 删除数据库记录
                        self.db.delete(backup)
                        cleaned_count += 1
                    
                    logger.info(f"设备 {device.name} 清理了 {len(backups_to_delete)} 个旧备份")
            
            # 提交数据库更改
            self.db.commit()
            logger.info(f"备份清理完成，共清理了 {cleaned_count} 个旧备份")
            
            return {
                "success": True,
                "cleaned_count": cleaned_count,
                "message": f"成功清理了 {cleaned_count} 个旧备份"
            }
            
        except Exception as e:
            self.db.rollback()
            logger.error(f"备份清理失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "message": f"备份清理失败: {str(e)}"
            }
    
    def get_backup_stats(self):
        """获取备份统计信息"""
        stats = {}
        
        # 获取所有设备
        devices = self.db.query(Device).all()
        
        for device in devices:
            # 获取该设备的备份数量
            backup_count = self.db.query(Backup).filter(
                Backup.device_id == device.id,
                Backup.status == 'success'
            ).count()
            
            stats[device.name] = {
                "device_id": device.id,
                "backup_count": backup_count,
                "max_allowed": self.max_backups_per_device,
                "needs_cleanup": backup_count > self.max_backups_per_device
            }
        
        return stats
    
    def cleanup_device_backups(self, device_id: int):
        """清理指定设备的旧备份"""
        try:
            device = self.db.query(Device).filter(Device.id == device_id).first()
            if not device:
                return {"success": False, "message": "设备不存在"}
            
            # 获取该设备的所有成功备份，按时间倒序
            backups = self.db.query(Backup).filter(
                Backup.device_id == device_id,
                Backup.status == 'success'
            ).order_by(desc(Backup.backup_time)).all()
            
            cleaned_count = 0
            
            if len(backups) > self.max_backups_per_device:
                backups_to_delete = backups[self.max_backups_per_device:]
                
                for backup in backups_to_delete:
                    # 删除文件
                    if os.path.exists(backup.filepath):
                        try:
                            os.remove(backup.filepath)
                        except Exception as e:
                            logger.error(f"删除文件失败 {backup.filepath}: {str(e)}")
                    
                    # 删除数据库记录
                    self.db.delete(backup)
                    cleaned_count += 1
                
                self.db.commit()
                logger.info(f"设备 {device.name} 清理了 {cleaned_count} 个旧备份")
            
            return {
                "success": True,
                "cleaned_count": cleaned_count,
                "message": f"设备 {device.name} 清理了 {cleaned_count} 个旧备份"
            }
            
        except Exception as e:
            self.db.rollback()
            logger.error(f"清理设备 {device_id} 备份失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "message": f"清理失败: {str(e)}"
            }
